/**
 * 
 */
package com.wachulski.marcin.msc.pl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;


/**
 * @author Marcin Wachulski
 *
 */
public final class PLScript {
	private final String name;
	private final String filepath;
	private final ArrayList<PLQuery> queries;
	
	public PLScript(String name, String filepath) {
		this.name = name;
		this.filepath = filepath;

		this.queries = new ArrayList<PLQuery>();
		
		try {
			BufferedReader reader = new BufferedReader(new FileReader(filepath));
			String input = null;
			String queryName = null;
			StringBuilder sb = null;
			boolean queryPos = true;
			while ((input = reader.readLine()) != null) {
				if (input.length() > 0 && input.charAt(0) == ';') {
					if (queryName != null && sb != null && queryPos)
						this.queries.add(new PLQuery(queryName, sb.toString()));
					if (input.charAt(1) == '-')
						queryPos = false;
					else
						queryPos = true;
					if (queryPos) {
						sb = new StringBuilder();
						queryName = input.substring(2);
					}
				}
				else if (queryPos)
					sb.append(input).append('\n');
			}
			if (queryName != null && !sb.equals("") && queryPos)
				this.queries.add(new PLQuery(queryName, sb.toString()));
			reader.close();
		}
		catch (Exception e) {}
	}
	
	/**
	 * @return the name
	 */
	public final String getName() {
		return name;
	}

	/**
	 * @return the body
	 */
	public final String getFilePath() {
		return filepath;
	}
	
	/**
	 * @return the queries
	 */
	public final ArrayList<PLQuery> getQueries() {
		return queries;
	}
}
